package edu.sdjzu.exam.service.redis;

import com.fasterxml.jackson.databind.ObjectMapper;
import edu.sdjzu.exam.dto.examSession.SaveDraftDTO;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class DraftRedisService {

    private final RedisTemplate<String, String> redisTemplate;
    private final ObjectMapper objectMapper;

    public void saveDraftToRedis(Long sessionId, SaveDraftDTO draftDTO) {
        try {
            String key = "exam:draft:" + sessionId + ":" + draftDTO.getQuestionId();
            Map<String, Object> draftData = new HashMap<>();
            draftData.put("answerContent", draftDTO.getAnswerContent());
            draftData.put("filePath", draftDTO.getFilePath());
            draftData.put("answerTime", draftDTO.getAnswerTime().toString());
            String value = objectMapper.writeValueAsString(draftData);
            redisTemplate.opsForValue().set(key, value, Duration.ofHours(1));
        } catch (Exception e) {
            throw new RuntimeException("保存草稿到 Redis 失败", e);
        }
    }

    public SaveDraftDTO getDraftFromRedis(Long sessionId, Long questionId) {
        try {
            String key = "exam:draft:" + sessionId + ":" + questionId;
            String value = redisTemplate.opsForValue().get(key);
            if (value == null) {
                return null;
            }
            Map<String, Object> draftData = objectMapper.readValue(value, HashMap.class);
            SaveDraftDTO draftDTO = new SaveDraftDTO();
            draftDTO.setSessionId(sessionId);
            draftDTO.setQuestionId(questionId);
            draftDTO.setAnswerContent((String) draftData.get("answerContent"));
            draftDTO.setFilePath((String) draftData.get("filePath"));
            draftDTO.setAnswerTime(LocalDateTime.parse((String) draftData.get("answerTime")));
            return draftDTO;
        } catch (Exception e) {
            throw new RuntimeException("从 Redis 获取草稿失败", e);
        }
    }
}
